package auctionClient;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Scanner;

import javax.crypto.Cipher;

import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;

import auctionServer.Notifier;
import auctionServer.ServerReplica;

public class ClientTimeStamp implements Runnable{

	private ServerSocket serverSocket;
	private int tcpPort;
	private String clientsKeyDir;
	private boolean oneMore=true;
	public ClientTimeStamp(int tcpPort, String clientsKeyDir){
		this.tcpPort=tcpPort;
		this.clientsKeyDir=clientsKeyDir;
	}
	
	public void run(){
		
		 try {
	            serverSocket = new ServerSocket(tcpPort);
		 } catch (IOException e) {
	            System.out.println("Could not listen on port: "+tcpPort);
	     }
		 
		 try {
		     	while(oneMore){

		     		TcpListenerConnection connection=new TcpListenerConnection(tcpPort, serverSocket.accept());
		            String response=new String(connection.getMessage());
		     		Scanner stringReader=new Scanner(response);
		     		
		     		if(stringReader.next().equals("!getTimestamp")){
		     			String timestamp=""+System.currentTimeMillis();
		     			byte[] signature=null;
		     			
		     			response="!timestamp "+stringReader.next()+" "+stringReader.next();
		     			
		     			response+=" "+timestamp;
		     			try {
							signature=signData(response.getBytes(), readKey());
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		     			
		     			response+=" "+signature;
		     			connection.appendMessage(response.getBytes());
		     			connection.disconnect();
		     		}else connection.disconnect();
		     	}
			 } catch (IOException e) {
		     	System.out.println("Server closed Accept failed: "+tcpPort);
			 }
	       
	}
	
	public byte[] signData(byte[] data, PrivateKey key) throws Exception {
	
		Signature sign = Signature.getInstance("SHA512withRSA");
		sign.initSign(key);
		sign.update(data);
		return (sign.sign());
	}
	
	public void close() throws IOException{
	    oneMore=false;
		serverSocket.close();
	}
	
	@SuppressWarnings("resource")
	private PrivateKey readKey() throws IOException{			
	
	/*
	 PEMReader inClientPrivateKey = new PEMReader(new FileReader(clientsKeyDir+Client.getUserName().trim()+".pem"), new PasswordFinder() {
	 
	
		@Override
		public char[] getPassword() {
			char[] res = "".toCharArray();
			try {
				res = new BufferedReader(new InputStreamReader(System.in)).readLine().toCharArray();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return res;
		}
	});
	*/
		PEMReader inClientPrivateKey = new PEMReader(new FileReader(clientsKeyDir + Client.getUserName()+ ".pem"), new PasswordFinder() {
			@Override
			public char[] getPassword() {
				char[] res = "".toCharArray();
				System.out.println("Enter pass phrase:");
				res ="12345".toCharArray();
				return res;
			}
		});
		KeyPair keyPair = (KeyPair) inClientPrivateKey.readObject();
		PrivateKey privateKey = keyPair.getPrivate();
	
	return privateKey;
	}
}
